import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//回显服务器UDP
public class Server {
    private DatagramSocket socket = null;
    public Server(int port) throws SocketException {
        socket = new DatagramSocket(port);//端口号
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //1.读请求
            DatagramPacket request = new DatagramPacket(new byte[1024],1024);
            socket.receive(request);//如果没有请求，就阻塞
            String r = new String(request.getData(),0,request.getLength());//得到真实长度
            //2.根据请求计算响应
            String response = process(r);
            //3.返回响应
            DatagramPacket res = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,request.getSocketAddress());
            // response.length()得到字符长度，response.getBytes().length得到字节长度
            // 网络传输以字节为单位进行操作
            socket.send(res);
            //4.打印日志
            System.out.printf("[%s:%d] req=%s,res=%s\n",
                    request.getAddress().toString(),request.getPort(),r,response);
            //为什么不close()？
            //socket是文件描述符表中的一个表象，因为我们不使用socket时，进程就要关闭，资源就全部释放了
        }
    }
    public String process(String request){
        return request;
    }
    public static void main(String[] args) throws IOException {
        Server server = new Server(9090);
        server.start();
    }
}
